package com.chain.qs.common.web;

import com.chain.qs.common.utils.CacheUtils;
import com.chain.qs.common.utils.StringUtils;
import com.google.common.collect.Maps;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.util.HashMap;
import java.util.Map;

/**
 * ws断开请求清除对应session 缓存
 */
@Component
public class WSSessionDisconnectEvent implements ApplicationListener<SessionDisconnectEvent> {

    @SuppressWarnings("unchecked")
    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {
        StompHeaderAccessor headers = StompHeaderAccessor.wrap(event.getMessage()); //获取消息头
        String disConnectedSessionId = (String) headers.getMessageHeaders().get("simpSessionId");
        Map<String, String> wsSessionMap = (Map<String, String>) CacheUtils.get("ws_sessions");
        wsSessionMap = (wsSessionMap == null ? Maps.newConcurrentMap() : wsSessionMap);
        if (StringUtils.isNoneBlank(disConnectedSessionId) && wsSessionMap.get(disConnectedSessionId) != null) {
            wsSessionMap.remove(disConnectedSessionId);
        }
    }
}
